package exteditapp.command;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import exteditapp.FileDefault;
import exteditapp.state.StateError;
import exteditapp.state.StateWaiting;

/**
 * Tries to upload editer file directly to plone server.
 * @author Arturas Smorgun, artuas@smorgun.lt
 */
public class CommandUpload extends ICommand {

	/**
	 * Default constructor
	 */
	public CommandUpload(FileDefault file){
		super(file);
	}

	/**
	 * Execution of upload to plone
	 * @return true on success and false otherwise
	 */
	public Boolean execute() {
		execution = true;
		//TODO implement plone upload procedure
		try {
			//init working files
			File original = file.getFileAsObject();
			File tmpUpload;
			FileInputStream in;
			FileOutputStream out;
			//create temporary file for uploading
			tmpUpload = File.createTempFile("extedit", file.getName());
			tmpUpload.deleteOnExit();
			in = new FileInputStream(original);
			out = new FileOutputStream(tmpUpload);
			//copy file contents into file for upload
			byte ch[] = new byte[1024];
			int currentCounter = 0;
			while((currentCounter = in.read(ch)) > 0){
				out.write(ch, 0, currentCounter);
			}
			out.close();
			in.close();
			//open connection with Plone serverURL 
			URL myUrl = new URL(file.getDownloadURL());
			HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
			connection.setRequestProperty("Connection", "close");
			connection.setRequestProperty("Content-length", Long.toString(original.length()));
			String lockPath = file.getModule().getSettings().getParameter("lockPath");
			String lockToken = file.getModule().getSettings().getParameter("lockToken");
			connection.setRequestProperty("If", "<"+lockPath+"> (<"+lockToken+">)");
			System.out.println("HEADER: "+"If " + "<"+lockPath+"> (<"+lockToken+">)");
			connection.setDefaultUseCaches(false);
			connection.setDoOutput(true);
			connection.setRequestMethod("PUT");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(3000);
			connection.setUseCaches(false);
			OutputStream outs = connection.getOutputStream();
			in = new FileInputStream(tmpUpload);
			int fileSize = (int)tmpUpload.length();
			int counter = 0;
			currentCounter = 0;
			while((currentCounter = in.read(ch)) > 0){
				counter += currentCounter;
				System.out.println((counter * 100 / fileSize) + " " + counter + " " + fileSize);
				this.file.getCurrentState().setProgress(counter * 100 / fileSize);
				outs.write(ch, 0, currentCounter);
			}
			outs.flush();
			in.close();
			InputStream ins = connection.getInputStream();
			while((currentCounter = ins.read(ch)) > 0){
				System.out.println(ch);
			}
			tmpUpload.delete();
			StateError newState = new StateError(this.file.getCurrentState().getIterator(), this.file);
			newState.setup("CHANGES SAVED", new StateWaiting(newState.getIterator(), newState.getFile(), false), 15);
			this.file.setCurrentState(newState);
			System.out.println("pabaiga");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		execution = false;
		this.file.getModule().getInvoker().setExecution(execution);
		return false;
	}

	/**
	 * Method for command execution invocation in separated thread
	 */
	public void run() {
		execute();
	}

}
